import { Injectable } from '@nestjs/common';
import AppEntity from '../db/entity/app.entity';
import {
  AppRequestDTO,
  AppSubmitDTO,
  AppRequestLateWithTypeDTO,
} from '../db/model/app.dto';
import dayjs = require('dayjs');
import { join } from 'path';
import { statSync, mkdirSync, createWriteStream, readFile } from 'fs';
import FileEntity from '../db/entity/file.entity';
import { CommonResponse, CommonResCode } from '../db/model/response.dto';
import { async } from 'rxjs/internal/scheduler/async';
// import FileInterface from '../common/interface/file';
import { currentDirPath } from '../common/utils/utils';
import plist = require('plist');
// import { Error } from 'mongoose';
import OSSUploadManger from '../common/utils/upload';
import * as config from '../common/utils/config';

interface FileInterface {
  originalname?: string;
  buffer?: Blob;
  size?: number;
  mimetype?: string;
  filedName?: string;
}

@Injectable()
export class AppService {
  submitApp = async (params: AppSubmitDTO) => {
    const fileEntity = await FileEntity.findOne(params.fileId);
    const model = new AppEntity();
    // tslint:disable-next-line:no-console
    console.log(params);
    model.name = params.name;
    model.desc = params.desc;
    model.file = fileEntity;
    model.systemType = params.systemType;
    model.appType = params.appType;
    model.build = params.build;
    model.uploadTime = dayjs().format('YYYY-MM-DD hh:mm');
    model.version = params.version;

    const obj = await model.save();
    return new CommonResponse(CommonResCode.Ok, obj, 'success');
  };

  uploadFiles = async (file: FileInterface[]) => {};

  uploadFile = async (body: AppRequestLateWithTypeDTO, file: FileInterface) => {
    const radom = (Math.random() * 900 + 100).toFixed();
    const baseDir = join('publish/web', dayjs().format('YYYYMMDD'));
    const component = radom + file.originalname;
    const pathKey = join(baseDir, component);
    // sql
    const fileEntity = new FileEntity();
    fileEntity.size = file.size;
    fileEntity.type = file.mimetype;

    // 上传oss
    // tslint:disable-next-line:no-any
    const resPathObj: any = await OSSUploadManger.uploadFile(
      pathKey,
      file.buffer,
    );
    fileEntity.path = resPathObj.key;
    console.log(resPathObj);

    // ios 特殊处理
    if (body.systemType == 2) {
      const plistComponent = radom + '-app.plist';
      const plistPathKey = join(baseDir, plistComponent);
      let appTitle = '井行学车';
      let bundleId = 'com.tuobaba.jx.students';
      if (body.appType == 2) {
        appTitle = '井行教练';
        bundleId = 'com.tuobaba.jx.coach';
      }

      const plistValue = await this.createInstallPlistFile(
        appTitle,
        bundleId,
        config.fileHost + `/${pathKey}`,
      );
      const resPlistObj: any = await OSSUploadManger.uploadFile(
        plistPathKey,
        plistValue,
      );
      fileEntity.plistPath = resPlistObj.key;
    }

    // let writeStream = createWriteStream(path);
    // writeStream.write(file.buffer);

    // 只保存文件后缀
    // let resPath = join('res/app',`${dayjs().format('YYYYMMDD')}`, component);

    // let fileEntity = new FileEntity();
    // fileEntity.size = file.size;
    // fileEntity.type = file.mimetype;
    // fileEntity.path = resPath;

    // if (body.systemType == 2) {
    //   let resPlistPath = join('res/app',`${dayjs().format('YYYYMMDD')}`, radom+'app.plist');
    //   fileEntity.plistPath = resPlistPath
    // }

    try {
      const result = await fileEntity.save();
      const resObj = new CommonResponse(CommonResCode.Ok, result, 'success');
      return resObj;
    } catch (error) {
      return new CommonResponse(CommonResCode.Ok, error, 'success');
    }
  };

  // 生成plist文件
  createInstallPlistFile(title: string, bundle: string, ipaUrl: string) {
    return new Promise<string>((resolve, reject) => {
      readFile(__dirname + '/xml/manifest.plist', async (err, pStr) => {
        if (err) {
          reject(new Error('无法打开文件'));
        }

        const plistJson: any = plist.parse(pStr.toString());
        const assets: any[] = plistJson.items[0].assets;
        const metaData: any = plistJson.items[0].metadata;

        const newAssets = assets.map((v, i) => {
          if (v.kind == 'software-package') {
            v.url = ipaUrl;
          } else if (v.kind == 'display-image') {
            v.url = 'https://file.abouti.top/icon/app512.png';
          } else {
            v.url = 'https://file.abouti.top/icon/app57.png';
          }
          return v;
        });

        let newMetaData = { ...metaData, 'bundle-identifier': bundle };
        newMetaData.title = title;
        // let a = {'bundle-identifier':bundle}
        // metaData.title = title;
        // metaData.bundle-identifier = ''

        const newJsonObj = { items: [{ assets: newAssets, metaData }] };
        const newPlistObj = plist.build(newJsonObj);

        resolve(newPlistObj);
      });
    });
  }
}
